package com.example.juc.controller;

import com.example.juc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author jl
 * @since 2021/9/17 23:04
 */
@Controller
public class TestController {

    @RequestMapping("/test")
    public String test(Model model) {
        User user1 = new User();
        user1.setId(1);
        user1.setName("bobo");
        User user2 = new User();
        user2.setId(2);
        user2.setName("boboSB");
        List<User> users = Arrays.asList(user1, user2);
        model.addAttribute("users", users);

        return "user";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 20, 1, TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(50), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
        CompletableFuture<Integer> exceptionally = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + " come in");
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 2;
        }, executor).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println("result = " + v);
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            return null;
        });
        // get()和join()都能获取返回结果，也都会阻塞
        // exceptionally.get(); // get()会抛出异常ExecutionException, InterruptedException
        // exceptionally.join(); // join()不会抛出异常，推荐使用join()获取结果
        // CompletableFuture要使用自定义创建的线程池，如果使用默认的线程池，则主线程结束后默认的线程池就会销毁，异步线程的代码就不会执行
        executor.shutdown();
        System.out.println("main thread over");
    }
}
